package at.fhj.mobsecdev.cookit.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import at.fhj.mobsecdev.cookit.R;
import at.fhj.mobsecdev.cookit.util.Constants;
import at.fhj.mobsecdev.cookit.webrequests.HashUtils;
import at.fhj.mobsecdev.cookit.webrequests.LoginWebCall;
import at.fhj.mobsecdev.cookit.webrequests.LoginWebCall.Login;

/**
 * Activity to log in and register
 */
public class LoginActivity extends Activity implements Login {

	private EditText username;
	private EditText password;
	private SharedPreferences credentialsSharedPreferences;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		/* If credentials are already stored and correct, immediately call MainActivity */
		credentialsSharedPreferences = getSharedPreferences(Constants.SHARED_PREFERNECES_CREDENTIALS, Context.MODE_PRIVATE);
		if(areCredentialsStored())
		{
			new LoginWebCall(credentialsSharedPreferences, this, LoginActivity.this).execute();
		}
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		
	}
	
	/**
	 * Stores login data and calls web service
	 * @param view
	 */
	public void login(View view)
	{
		credentialsSharedPreferences.edit()
		.putString(Constants.PREFERENCE_USERNAME, username.getText().toString())
		.putString(Constants.PREFERENCE_PASSWORDHASH, HashUtils.hashPlaintextPassword(password.getText().toString()))
		.commit();
		
		new LoginWebCall(credentialsSharedPreferences, this, LoginActivity.this).execute();		
	}

	/**
	 * Navigates back to MainActivity (recipe list)
	 */
	private void navigateToMainActivity()
	{
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
	}
	
	/**
	 * Forwards user to Register activity
	 * @param view
	 */
	public void onRegister(View view) {
		Intent intent = new Intent(this, RegistrationActivity.class);
		startActivity(intent);
	}

	/**
	 * Checks, whether credentials are already stored
	 * @return true, if already stored
	 */
	private boolean areCredentialsStored()
	{
		if(credentialsSharedPreferences.contains(Constants.PREFERENCE_USERNAME) &&
				credentialsSharedPreferences.contains(Constants.PREFERENCE_PASSWORDHASH))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/* Callback methods of Login Web Service */
	
	@Override
	public void credentialsCorrect() {
		navigateToMainActivity();
	}

	@Override
	public void credentialsIncorrect() {
		Toast.makeText(this, getResources().getString(R.string.error_credentials_incorrect), Toast.LENGTH_LONG).show();
	}

	@Override
	public void webServiceCallFailed(Exception e) {
		Toast.makeText(this, e.getMessage() , Toast.LENGTH_LONG).show();
	}
}
